﻿using GenericRepositoryUnitOfWorkDemo.Domain.Abstracts.UnitOfWorks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;

namespace GenericRepositoryUnitOfWorkDemo.Infrastructure.Abstracts.UnitOfWorks;

public class UnitOfWork<TDbContext> : IUnitOfWork, IDisposable
    where TDbContext : DbContext
{
    private readonly TDbContext _dbContext;
    private IDbContextTransaction DbContextTransaction { get; set; }

    public UnitOfWork(TDbContext context)
    {
        _dbContext = context ?? throw new ArgumentNullException(nameof(context));
    }

    public IDbContextTransaction BeginTransaction()
    {
        if (DbContextTransaction == null)
        {
            DbContextTransaction = _dbContext.Database.BeginTransaction();
        }
        return DbContextTransaction;
    }

    public void Commit()
    {
        if (DbContextTransaction == null)
        {
            return;
        }

        DbContextTransaction.Commit();
    }

    public void Dispose()
    {
        if (DbContextTransaction == null)
        {
            return;
        }

        DbContextTransaction.Dispose();
    }
}

public class UnitOfWorkInner : IUnitOfWork
{
    private readonly IUnitOfWork _unitOfWorkOuter;

    public UnitOfWorkInner(IUnitOfWork unitOfWorkOuter)
    {
        _unitOfWorkOuter = unitOfWorkOuter;
    }

    public IDbContextTransaction BeginTransaction()
    {
        return _unitOfWorkOuter.BeginTransaction();
    }

    public void Commit()
    {

    }

    public void Dispose()
    {

    }
}